local UIDebrisList      = UIBase.New(PanelResNames.UIDebrisList)
local fragMgr           = StrangeFragmentManager

local chip_info         = nil
local cur_list          = nil

local chips_btn_frames  = {}
local item_list         = {}
local current_select    = nil
local this              = UIDebrisList
local m_job_btns        = {}
local m_list_skill      = {}
local m_sub_skills      = {}

local const_state       = {null = 0, change = 1, remove = 2}
local const_quality     = {SR = 4, SSR = 6, UR = 8, LR = 10, LRPlus = 16}
local m_attr            = {}

local m_select_quality   = nil
local clickType = nil

local sort_func = function(a,b)
    if a.quality ~= b.quality then
        return a.quality > b.quality
    else
        if a.level ~= b.level then
            return  a.level > b.level
        end
    end
    return a.itemId > b.itemId
end

function UIDebrisList.Init(data, _goFunc)
    chip_info = data
    UIDebrisList.goFunc = _goFunc;
    UIBase.Init(UIDebrisList)
end

function UIDebrisList:OnCreate()
    self:RegisterOnClick(self:GetChild("bgclose"), self.OnClick_close)
    self:RegisterOnClick(self:GetChild("bgClose"), self.OnClick_close)
    
    -- self:RegisterOnClick(self:GetChild("btnQuality"), self.OnClick_close)
    self:RegisterOnClick(self:GetChild("btnQuality"), self.OnClick_arrow)
    self:RegisterOnClick(self:GetChild("btnLevelUp"), self.OnClick_levelUp)
    self:RegisterOnClick(self:GetChild("btnBaptism"), self.OnClick_baptism)
    self:RegisterOnClick(self:GetChild("btnPutOn"),   self.OnClick_equip)
    self:RegisterOnClick(self:GetChild("btnChange"),  self.OnClick_change)
    self:RegisterOnClick(self:GetChild("btnRemove"),  self.OnClick_remove)
    self:RegisterOnClick(self:GetChild("btnJump"),    self.onClickSource)
    
    self.btn_change     = self:GetChild("btnChange")
    self.scroll_list    = self:GetChild("list")
    self.scroll_list:SetVirtual()
    self.btn_SR         = self:GetChild("btnSR")
    self.btn_SSR        = self:GetChild("btnSSR")
    self.btn_UR         = self:GetChild("btnUR")
    self.btn_LR         = self:GetChild("btnLR")
    self.btn_LRPlus     = self:GetChild("btnLRPlus")
    self.equipListitem  = self:GetChild("equipListitem")
    self.btn_lock       = self.equipListitem:GetChild("btnLock")
    self.txt_name       = self.equipListitem:GetChild("name")
    self.scroll_skill   = self.equipListitem:GetChild("listSkill")
    self.listSubSkill   = self.equipListitem:GetChild("listSubSkill")
    self.txt_equip_hint = self.equipListitem:GetChild("title21")
    self.power          = self.equipListitem:GetChild("power")
    self.ctrlSubSkill   = self.equipListitem:GetController("subSkill")
    self.txt_type_title = self:GetChild("typeTitle")

    self:RegisterOnClick(self.btn_lock,   self.OnClick_lock)

    self.ctr_sort       = self:GetController("sort")
    self.ctr_nothing    = self:GetController("nothing")
    this.ctr_state      = self:GetController("state")
    this.ctr_c1         = self:GetController("c1")
    self.inlayItem      = self:GetChild("item")
    self.inlay_child    = self.inlayItem:GetChild("item")

    self.sourceUIobj    = self:GetChild("UISourceMultiple");
    self.showSourceController = self:GetController("showSource")
    this.effectController = self:GetController("effect", self:GetChild("btnJump"));
    self.ctr_attr       = self.equipListitem:GetController("attr")
    this.attrlist       = self.equipListitem:GetChild("attrlist")
    self.ctr_attr.selectedIndex = 1

    self.tipCtrl = self:GetController("tips")
    self.tipItem1 = self:GetChild("UIChangeDebrisOwner/equip1")
    self.tipItem2 = self:GetChild("UIChangeDebrisOwner/equip2")
    self.tipIcon1 = self:GetChild("UIChangeDebrisOwner/equip1hero/HeadIcon")
    self.tipIcon2 = self:GetChild("UIChangeDebrisOwner/equip2hero/HeadIcon")
    self.tipText = self:GetChild("UIChangeDebrisOwner/tipText")

    self:RegisterOnClick(self.btn_SSR, function()
        self:OnClick_selectQuality(const_quality.SSR)
    end)
    self:RegisterOnClick(self.btn_UR, function()
        self:OnClick_selectQuality(const_quality.UR)
    end)
    self:RegisterOnClick(self.btn_LR, function()
        self:OnClick_selectQuality(const_quality.LR)
    end)

    self:RegisterOnClick(self.btn_SR, function()
        self:OnClick_selectQuality(const_quality.SR)
    end)
    self:RegisterOnClick(self.btn_LRPlus, function()
        self:OnClick_selectQuality(const_quality.LRPlus)
    end)
    self:RegisterOnClick(self:GetChild("UIChangeDebrisOwner/btn_cancel"),function()
        self.tipCtrl.selectedIndex = 0
    end)
    self:RegisterOnClick(self:GetChild("UIChangeDebrisOwner/n0"),function()
        self.tipCtrl.selectedIndex = 0
    end)
    self:RegisterOnClick(self:GetChild("UIChangeDebrisOwner/btn_sure"),function()
        if clickType == 1 then
            weaponHandler.ReqFragmentReplace(chip_info.heroId, current_select.partnerId)
        else
            local cur_chip = current_select
            local _inlayFragment = StrangeFragmentManager.GetCurrentEquipFragment(current_select.partnerId)
            if _inlayFragment then
                weaponHandler.ReqFragmentDemount(current_select.partnerId, current_select.itemId)
            end
            weaponHandler.ReqFragmentInlay(chip_info.heroId, cur_chip.itemId)--装备
        end
        self.tipCtrl.selectedIndex = 0
    end)
    local btn = nil
    m_job_btns = {}
    for i=1, 5 do
        btn = self:GetChild("btn" .. (i - 1))

        btn.onChanged:Add(function()
            this.OnClick_filterJob(i - 1)
        end)
        table.insert(m_job_btns, btn)
    end

    chips_btn_frames[4]     = self.btn_SR
    chips_btn_frames[6]     = self.btn_SSR
    chips_btn_frames[8]     = self.btn_UR
    chips_btn_frames[10]    = self.btn_LR
    chips_btn_frames[16]    = self.btn_LRPlus

    this.scroll_skill.itemRenderer = this.SetSkillData
    this.listSubSkill.itemRenderer = this.SetSubSkillData

    cur_list = fragMgr.GetWeaponFragmentList(chip_info.heroId)
    table.sort(cur_list, sort_func)

    current_select = chip_info.gemInfo
    -- if #cur_list > 0 then
    --     current_select = cur_list[1]
    -- end
    this.job_type = 0

    this.scroll_list.itemRenderer = this.SetData
    this.attrlist.itemRenderer = this.AttrRender
   
    UIDebrisList.RefreshTopItem(current_select)
end

function UIDebrisList.RefreshAttr(chip)
    if chip then
        this.ctr_attr.selectedIndex = 1
        local als = chip.GetAttr()
        local bls = StrangeFragmentManager.GetChipAttr(chip.itemModelId, 1)
        m_attr = {}
        if als then
            for k,v in pairs(als) do
                table.insert(m_attr, {basic = bls[k], now = v})
            end
        end
        
        this.attrlist.numItems = #m_attr
    else
        this.ctr_attr.selectedIndex = 0
    end
end

function UIDebrisList.AddEvent()
    ListenEvent(Config.EventType.Fragment_Unwear, this.Refresh)
    ListenEvent(Config.EventType.Fragment_Wear, this.Refresh)
    ListenEvent(Config.EventType.Fragment_Replace, this.OnReplace)
    ListenEvent(Config.EventType.DebrisUpdate, this.Refresh)
end

function UIDebrisList.RemoveEvent()
    CloseEvent(Config.EventType.Fragment_Unwear, this.Refresh)
    CloseEvent(Config.EventType.Fragment_Wear, this.Refresh)
    CloseEvent(Config.EventType.Fragment_Replace, this.OnReplace)
    CloseEvent(Config.EventType.DebrisUpdate,this.Refresh)
end

function UIDebrisList.OnReplace()
    this.Refresh()
end

function UIDebrisList:OnEnable()
    current_select = chip_info.gemInfo

    UIDebrisList.AddEvent()

    m_select_quality = nil

    UIDebrisList.RefreshState()
    UIDebrisList.Refresh()
end

function UIDebrisList.OnDisable()
    current_select = nil
    UIDebrisList.RemoveEvent()
end

function UIDebrisList.Refresh()
    local itemId = fragMgr.GetCurrentEquipFragment(chip_info.heroId)
    if chip_info.gemInfo ~= itemId then
        chip_info.gemInfo = itemId
    end
    
    if current_select then
        this.inlayItem:GetController("state").selectedIndex = 1

        local item = CtrlManager.GetCtrl(PanelNames.Item);
        if item ~= nil and itemId then
            -- item.initData(this.inlay_child,itemId,1,false,nil,chip_info.heroId);
            fragMgr.SetItemData(this.inlay_child, itemId, false)
            this.inlay_child.onClick:Clear()
        end

    else
        this.inlayItem:GetController("state").selectedIndex = 0
        this.inlay_child:GetController("state").selectedIndex = 0
    end

    cur_list = fragMgr.GetWeaponFragmentList(chip_info.heroId)
    table.sort(cur_list, sort_func)
    if #cur_list == 0 then
        this.effectController.selectedIndex = 1;
        this.ctr_nothing.selectedIndex = 1
    else
        this.effectController.selectedIndex = 0;
        this.ctr_nothing.selectedIndex = 0

        UIDebrisList.OnClick_filterJob(this.job_type, m_select_quality)
        -- this.scroll_list.itemRenderer = this.SetData
        -- this.scroll_list.numItems = #cur_list
    end
    UIDebrisList.RefreshState()
end

function UIDebrisList.SetSkillData(index, obj)
    local skill = m_list_skill[index + 1]
    local txt = obj:GetChild("textSkillType")
    if skill.mianSkill then
        txt.text = current_select.GetMainSkillDes()
    else
        txt.text = current_select.GetSubSkillDes(skill.skillId)
    end
end

function UIDebrisList.SetSubSkillData(index, obj)
    local txtDesc = obj:GetChild("textSkillType")
    local skillData = m_sub_skills[index + 1]
    local id, value = skillData.skillId, skillData.val
    local cfg = dataTable.getDataTableByStringId("t_debrisminorskill", tostring(id))
    txtDesc.text = cfg and string.format(getLanguage(cfg.f_text), value * cfg.f_muti * 0.0001) or ""
end

function UIDebrisList.RefreshTopItem(info)
    local item = CtrlManager.GetCtrl(PanelNames.Item);
    if info then
        this.inlayItem:GetController("state").selectedIndex = 1
       
        if item ~= nil then
            -- item.initData(this.inlay_child, info,1,false,nil,chip_info.heroId);
            fragMgr.SetItemData(this.inlay_child, info, false)
            this.inlay_child.onClick:Clear()
        end
        this.ctr_c1.selectedIndex = 1

        if current_select and current_select.partnerId == chip_info.heroId then
            this.ctr_c1.selectedIndex = 1
            this.txt_equip_hint.text = "当前装备"

        else
            this.ctr_c1.selectedIndex = 1
            this.txt_equip_hint.text = ""
        end
        this.txt_name.text = info.colorname
        this.power.text = getNumString(info.addPower)

        m_list_skill = info.skillList
        this.scroll_skill.numItems = #m_list_skill

        this.ctrlSubSkill.selectedIndex = 0
        m_sub_skills = info.subSkills
        if m_sub_skills and #m_sub_skills > 0 then
            this.listSubSkill.numItems = #m_sub_skills
            this.ctrlSubSkill.selectedIndex = 1
        end
        
        UIDebrisList.btn_lock.selected = info.lock == 1

        if info == chip_info.gemInfo then
            this.btn_change.grayed = true
        else
            this.btn_change.grayed = false
        end
        this.RefreshAttr(info)
    else
        this.RefreshAttr()
        this.inlayItem:GetController("state").selectedIndex = 0
        this.ctr_c1.selectedIndex = 0
    end
end

function UIDebrisList.AttrRender(index, obj)
    local txt_name = obj:GetChild("name")
    local txt_value = obj:GetChild("value")
    local txt_refine = obj:GetChild("refine")

    local attr = m_attr[index + 1]
    local at = G.dataTable["t_attributelibrary"][tostring(attr.now[1])]
    if at then
        local basic = attr.basic and attr.basic[2] or 0
        txt_name.text = at.f_AttributeName
        txt_refine.text = basic
        local delta = attr.now[2] - basic
        if delta == 0 then
            txt_value.text = ""
        else
            local type = at.f_AttributeType
            if type == 2 then
                txt_value.text =  "+" .. delta * 0.01 .. "%"
            else
                txt_value.text =  "+" .. delta
            end
        end
    end
end

--初始化物品信息
function UIDebrisList.SetData(index,obj)
    local item = CtrlManager.GetCtrl(PanelNames.Item);
    if item ~= nil then
        local chip = cur_list[index + 1]

        fragMgr.SetItemData(obj, chip, true)

        if current_select == chip then
            obj:GetController("state").selectedIndex = 1
        end

        obj.onClick:Clear()
        obj.onClick:Add(function()
            -- if fragMgr.GetBaptismStatus() == Config.Baptism_Step.None then
                if current_select ~= chip then
                    for k,v in pairs(item_list) do
                        v.obj:GetController("state").selectedIndex = 0
                    end

                    current_select = chip
                    UIDebrisList.RefreshState()
                    UIDebrisList.RefreshTopItem(chip)
    
                    obj:GetController("state").selectedIndex = 1
                else
                    if current_select == chip_info.gemInfo then
                        if obj:GetController("state").selectedIndex == 0 then
                            obj:GetController("state").selectedIndex = 1
                        else
                            obj:GetController("state").selectedIndex = 0
                        end
                    else
                        current_select = chip_info.gemInfo
                        obj:GetController("state").selectedIndex = 0
                    end
                    
                    UIDebrisList.RefreshState()
                    UIDebrisList.RefreshTopItem(current_select)
                end
            -- else
            --     current_select = chip
            --     FireEvent(Config.EventType.Fragment_Select_Item, current_select)
            --     closeUI(PanelResNames.UIDebrisList)
            -- end
        end)

        item_list[index] = {item = item, obj = obj}
    end
end

function UIDebrisList.RefreshState()
    if chip_info.gemInfo then
        if current_select then
            this.ctr_c1.selectedIndex = 1
        end
        this.ctr_state.selectedIndex = 1
    else
        this.ctr_state.selectedIndex = 0
    end
end

function UIDebrisList:OnDestroy(  )
   
end

function UIDebrisList:OnClick_close()
    closeUI(PanelResNames.UIDebrisList)
    current_select = nil
end

function UIDebrisList:OnClick_arrow()
    self.ctr_sort.selectedIndex = self.ctr_sort.selectedIndex  == 0 and 1 or 0
end

function UIDebrisList:OnClick_levelUp()
    if current_select == nil then
        UISysTips.AddMsg(getLanguage("请先选择需要升级的英灵魂晶"))
        return
    end
    if current_select then
        showUI(PanelNames.UIDebrisLevelUp, current_select)
        -- closeUI(PanelResNames.UIDebrisList)
    else
        UISysTips.AddMsg(getLanguage("UIEquip_HadNotGem"))
    end
end

function UIDebrisList:CliclTip()
    self.tipCtrl.selectedIndex = 1
    local other = HeroManager.getHeroDatabyPartnerId(current_select.partnerId)
    local now= HeroManager.getHeroDatabyPartnerId(chip_info.heroId)
    self.tipIcon1.url = EnumConst.AtlasPath.ICONAtlas..other.icon
    self.tipIcon2.url = EnumConst.AtlasPath.ICONAtlas..now.icon
    fragMgr.SetItemData(self.tipItem1, current_select, false)
    fragMgr.SetItemData(self.tipItem2, current_select, false)
    self.tipText.text = string.format(string.gsub(getLanguage("CommonPop_Tips59"),"\\n","\n",9),other.name, current_select.name,now.name)
end

function UIDebrisList:OnClick_equip()
    if current_select == nil then
        UISysTips.AddMsg(getLanguage("DebrisText23"))
        return
    end
    local cur_chip = current_select
    if cur_chip then
        if current_select.partnerId then
            clickType = 2
            self:CliclTip()
        else
            weaponHandler.ReqFragmentInlay(chip_info.heroId, cur_chip.itemId)--装备
        end
    else
        UISysTips.AddMsg(getLanguage("UIEquip_HadNotGem"))
    end
end

function UIDebrisList:OnClick_change()
    if current_select == nil then
        UISysTips.AddMsg(getLanguage("请先选择需要替换的英灵魂晶"))
        return
    end
    if current_select then
        if current_select.partnerId then
            if current_select.partnerId ~= chip_info.heroId then
                clickType = 1
                self:CliclTip()
            end
        else
            weaponHandler.ReqFragmentInlay(chip_info.heroId, current_select.itemId)--装备
        end
    end
end

function UIDebrisList:OnClick_remove()
    if chip_info.gemInfo then
        weaponHandler.ReqFragmentDemount(chip_info.heroId, chip_info.gemInfo.itemId)--卸下
    end
end

function UIDebrisList:OnClick_lock()
    if current_select then
        local lock = current_select.lock == 1 and 0 or 1
        weaponHandler.ReqLockDebris(current_select.partnerId, current_select.itemId, lock)
    end
end

--洗练
function UIDebrisList:OnClick_baptism()
    if current_select == nil then
        return
    end

    showUI(PanelNames.UIDebrisBaptism, current_select)
end

local chips_quality_map = {}
function UIDebrisList:OnClick_selectQuality(quality)
    m_select_quality = quality

    for k,v in pairs(chips_btn_frames) do
        if k == quality then
            v.selected = true
        else
            v.selected = false
        end
    end

    if this.job_type and this.job_type ~= 0  then
        cur_list = fragMgr.FilterProfession(this.job_type, quality)
    else
        cur_list = fragMgr.FilterQuality(quality)
    end
    
    table.sort(cur_list, sort_func)
    if #cur_list == 0 then
        this.ctr_nothing.selectedIndex = 1
    else
        this.ctr_nothing.selectedIndex = 0
        this.scroll_list.numItems = #cur_list
    end
end

function UIDebrisList.OnClick_filterJob(type)
    this.job_type = type

    if type == 0 then
        m_select_quality = nil
        for k,v in pairs(chips_btn_frames) do
            v.selected = false
        end
    end

    for k,v in pairs(m_job_btns) do
        if k - 1 == type then
            v.selected = true
        else
            v.selected = false
        end
    end
    this.txt_type_title.text = getLanguage("DebrisType" .. type)

    cur_list = fragMgr.FilterProfession(type, m_select_quality)

    table.sort(cur_list, sort_func)
    if #cur_list == 0 then
        this.ctr_nothing.selectedIndex = 1
    else
        this.ctr_nothing.selectedIndex = 0
        this.scroll_list.numItems = #cur_list
    end
end

function UIDebrisList:onClickSource()
    --showUI(PanelNames.UISource, function ()
    --    if self.goFunc then
    --        self.goFunc();
    --    end
    --end, self.hero.storeId);
    self.showSourceController.selectedIndex = 1;
    self.showSourceList = {200428}
    logicMgr.ItemManager.setSourceStart("UICharactorInfoHeroBreak", true);
    self:updateSource();
end

function UIDebrisList:updateSource()
    logicMgr.ItemManager.updateSourceUI(self.sourceUIobj, self.showSourceList, function ()
        self.showSourceController.selectedIndex = 0;
    end, function ()
        self.showSourceController.selectedIndex = 0;
        self:OnClick_close();
        if self.goFunc then
            self.goFunc();
        end
    end );
end
return UIDebrisList